args unique_id

* stores regulation year for each state. 3000 if never implemented
sort `unique_id' year
by `unique_id': egen reg_year = min(year* (PostReg1==1) + 3000*(PostReg1 == 0)) 
by state_id: egen temp = min(reg_year)
replace reg_year = temp
drop temp

* 2 years before and 2 years after the regulation
gen year_post_reg = year - reg_year if reg_year ~= 3000
replace year_post_reg = . if inrange(year_post_reg, -$wsize, $wsize) ==0
replace year_post_reg = year_post_reg + $wsize 
